<template>
  <div class="income-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>收入管理</span>
          <div class="header-operations">
            <el-button type="primary" @click="handleExport">导出明细</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="queryParams" ref="queryForm" :inline="true" class="search-form">
        <el-form-item label="收入类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="请选择收入类型" clearable>
            <el-option
              v-for="item in incomeTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="收入渠道" prop="channel">
          <el-select v-model="queryParams.channel" placeholder="请选择收入渠道" clearable>
            <el-option
              v-for="item in incomeChannels"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围" prop="timeRange">
          <el-date-picker
            v-model="queryParams.timeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 收入统计卡片 -->
      <el-row :gutter="20" class="statistics-cards">
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>总收入</span>
              </div>
            </template>
            <div class="statistics-content">
              <div class="amount">¥ {{ statistics.totalIncome }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>订单收入</span>
              </div>
            </template>
            <div class="statistics-content">
              <div class="amount">¥ {{ statistics.orderIncome }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>会员收入</span>
              </div>
            </template>
            <div class="statistics-content">
              <div class="amount">¥ {{ statistics.memberIncome }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>其他收入</span>
              </div>
            </template>
            <div class="statistics-content">
              <div class="amount">¥ {{ statistics.otherIncome }}</div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 收入趋势图 -->
      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>收入趋势</span>
            <el-radio-group v-model="chartType" size="small">
              <el-radio-button label="daily">日收入</el-radio-button>
              <el-radio-button label="weekly">周收入</el-radio-button>
              <el-radio-button label="monthly">月收入</el-radio-button>
            </el-radio-group>
          </div>
        </template>
        <div class="chart-container" ref="incomeChartRef"></div>
      </el-card>

      <!-- 收入明细表格 -->
      <el-table
        v-loading="loading"
        :data="incomeList"
        style="width: 100%"
        border
      >
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="orderNo" label="订单编号" width="180" />
        <el-table-column prop="type" label="收入类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getIncomeTypeTag(row.type)">
              {{ getIncomeTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="channel" label="收入渠道" width="120">
          <template #default="{ row }">
            {{ getIncomeChannelLabel(row.channel) }}
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="收入金额" width="120">
          <template #default="{ row }">
            ¥ {{ row.amount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="收入时间" width="180" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              @click="handleDetail(row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 收入详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="收入详情"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单编号">{{ detail.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="收入类型">
          <el-tag :type="getIncomeTypeTag(detail.type)">
            {{ getIncomeTypeLabel(detail.type) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="收入渠道">
          {{ getIncomeChannelLabel(detail.channel) }}
        </el-descriptions-item>
        <el-descriptions-item label="收入金额">
          ¥ {{ detail.amount?.toFixed(2) }}
        </el-descriptions-item>
        <el-descriptions-item label="收入时间">{{ detail.createTime }}</el-descriptions-item>
        <el-descriptions-item label="支付方式">{{ detail.paymentMethod }}</el-descriptions-item>
        <el-descriptions-item label="交易流水号">{{ detail.transactionNo }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="detail.status === 1 ? 'success' : 'danger'">
            {{ detail.status === 1 ? '已到账' : '未到账' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detail.remark }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { getIncomeList, exportIncomeList, getIncomeCategoryStatistics, getIncomeChannelStatistics } from '@/api/finance'

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  type: undefined,
  channel: undefined,
  timeRange: []
})

// 收入类型选项
const incomeTypes = [
  { label: '订单收入', value: 'ORDER' },
  { label: '会员收入', value: 'MEMBER' },
  { label: '其他收入', value: 'OTHER' }
]

// 收入渠道选项
const incomeChannels = [
  { label: '微信支付', value: 'WECHAT' },
  { label: '支付宝', value: 'ALIPAY' },
  { label: '银行卡', value: 'BANK' },
  { label: '现金', value: 'CASH' }
]

// 统计数据
const statistics = ref({
  totalIncome: 0,
  orderIncome: 0,
  memberIncome: 0,
  otherIncome: 0
})

// 图表相关
const incomeChartRef = ref(null)
let incomeChart = null
const chartType = ref('daily')

// 表格数据
const loading = ref(false)
const incomeList = ref([])
const total = ref(0)

// 详情对话框
const detailDialogVisible = ref(false)
const detail = ref({})

// 获取收入类型标签
const getIncomeTypeTag = (type) => {
  const map = {
    ORDER: 'success',
    MEMBER: 'warning',
    OTHER: 'info'
  }
  return map[type] || 'info'
}

// 获取收入类型标签文本
const getIncomeTypeLabel = (type) => {
  const item = incomeTypes.find(item => item.value === type)
  return item ? item.label : type
}

// 获取收入渠道标签文本
const getIncomeChannelLabel = (channel) => {
  const item = incomeChannels.find(item => item.value === channel)
  return item ? item.label : channel
}

// 查询列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getIncomeList(queryParams.value)
    incomeList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取收入列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取统计数据
const getStatistics = async () => {
  try {
    const [categoryRes, channelRes] = await Promise.all([
      getIncomeCategoryStatistics(queryParams.value),
      getIncomeChannelStatistics(queryParams.value)
    ])
    statistics.value = categoryRes.data
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 初始化收入趋势图
const initIncomeChart = async () => {
  if (!incomeChartRef.value) return
  
  incomeChart = echarts.init(incomeChartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data: [],
      type: 'line',
      smooth: true,
      areaStyle: {}
    }]
  }
  
  incomeChart.setOption(option)
  
  // 获取收入趋势数据
  try {
    const res = await getIncomeTrend({
      timeRange: queryParams.value.timeRange,
      type: chartType.value
    })
    const { data } = res
    incomeChart.setOption({
      xAxis: {
        data: data.dates
      },
      series: [{
        data: data.amounts
      }]
    })
  } catch (error) {
    console.error('获取收入趋势数据失败:', error)
  }
}

// 查询按钮点击
const handleQuery = () => {
  queryParams.value.pageNum = 1
  getList()
  getStatistics()
  initIncomeChart()
}

// 重置按钮点击
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    type: undefined,
    channel: undefined,
    timeRange: []
  }
  handleQuery()
}

// 导出按钮点击
const handleExport = async () => {
  try {
    const res = await exportIncomeList(queryParams.value)
    const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = '收入明细.xlsx'
    link.click()
    window.URL.revokeObjectURL(link.href)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 查看详情
const handleDetail = (row) => {
  detail.value = row
  detailDialogVisible.value = true
}

// 分页大小改变
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  getList()
}

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val
  getList()
}

// 监听图表类型变化
watch(chartType, () => {
  initIncomeChart()
})

// 监听窗口大小变化
const handleResize = () => {
  incomeChart?.resize()
}

onMounted(() => {
  handleQuery()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  incomeChart?.dispose()
})
</script>

<style lang="scss" scoped>
.income-container {
  padding: 20px;
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .search-form {
    margin-bottom: 20px;
  }
  
  .statistics-cards {
    margin-bottom: 20px;
    
    .statistics-content {
      text-align: center;
      
      .amount {
        font-size: 24px;
        font-weight: bold;
        color: #303133;
        margin: 10px 0;
      }
    }
  }
  
  .chart-card {
    margin-bottom: 20px;
    
    .chart-container {
      height: 400px;
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style> 